import { defineStore } from 'pinia'
import { ref } from 'vue'
import { RouteRecordRaw } from 'vue-router'

type Tab = {
  path: string
  title: string
}
const useAppstore = defineStore('app', () => {
  /* state状态数据 */
  //所有访问数据的页面tab信息数组
  const tabs = ref<Tab[]>([{ path: '/dashboard', title: '首页' }])

  /*action方法 */
  //添加访问页面的tab信息
  const addTab = (route: RouteRecordRaw) => {
    //判断在所有已访问tab中是否存在当前正访问的路由信息
    //如果已经存在，则无需额外添加
    //如果不存在，则将其添加保存到数组中
    const has = tabs.value.some((tab: Tab) => tab.path === route.path)
    if (!has) {
      tabs.value.push({
        path: route.path,
        title: (route.meta?.title as string) ?? route.path,
      })
    }
  }

  //移除 tabs 数组中的访问标签信息
  const removeTab = (name: string) => {
    if (name !== '/dashboard') {
      tabs.value = tabs.value.filter((tab) => tab.path !== name)
    }
  }
  return {
    tabs,
    addTab,
    removeTab,
  }
})

export default useAppstore
